/*
 * Copyright 2018 The JA-SIG Collaborative. All rights reserved.
 * distributed with thi file and available online at
 */
package com.lap.codegen.ao.impl;

import com.lap.codegen.ao.FileAO;
import com.lap.codegen.core.ContextManager;
import com.lap.codegen.core.DbManager;
import com.lap.codegen.core.FileManager;
import com.lap.codegen.domain.CodeContext;
import com.lap.codegen.domain.CoreFile;
import com.lap.codegen.domain.DbConf;
import com.lap.codegen.utils.Constants;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;

/**
 * <pre>
 * 默认文件实现类
 * </pre>
 *
 * @author 劳水生 , 021(poker0325@me.com)
 * @version 1.0.0
 */
@Service("fileAO")
@AllArgsConstructor
public class DefaultFileAO implements FileAO {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 判断是否在执行
     */
    private final AtomicBoolean execute = new AtomicBoolean(false);
    /**
     * 文件业务对象
     */
    private final FileManager fileManager;
    /**
     * 上下文业务对象
     */
    private final ContextManager contextManager;
    /**
     * 数据库业务对象
     */
    private final DbManager dbManager;

    @Override
    public List<CoreFile> writeFile() {
        List<CoreFile> fileList = Collections.emptyList();
        if (execute.getAndSet(true)) {
            return fileList;
        }
        try {
            CodeContext context = contextManager.init();
            DbConf dbConf = context.getDb();
            List<String> tableNames = this.getTables(dbConf);
            if (Objects.nonNull(tableNames)) {
                context.setTableList(dbManager.queryByTableName(dbConf, tableNames));
                fileManager.writerFile(context);
                fileList = context.getFileList();
            }
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e);
        }
        return fileList;
    }


    /**
     * <pre>
     * 解析配置的表，业务：
     * 1、如果配置的是*，那么查询所有的表。
     * 2、否则就是根据配置来加载表。
     * </pre>
     *
     * @param conf 数据库配置
     * @return 需要生成代码表名
     */
    private List<String> getTables(DbConf conf) {
        if (Objects.nonNull(conf) && Objects.nonNull(conf.getTables())) {
            if (conf.getTables().contains(Constants.DOC)) {
                return new ArrayList<>(1);
            } else {
                String[] tempArray = conf.getTables().split(",");
                List<String> dataList = new LinkedList<>();
                Stream.of(tempArray).forEach(e -> dataList.add(e));
                return dataList;
            }
        } else {
            return null;
        }
    }

}
